#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/kprobes.h>
#include <linux/ktime.h>

// 用于存储kprobe信息的结构体
static struct kprobe kp;

// 全局变量，用于存储函数开始的时间
static ktime_t start_time;

// pre_handler，在函数执行前调用，记录开始时间
static int pre_handler(struct kprobe *p, struct pt_regs *regs)
{
    start_time = ktime_get(); // 记录开始时间
    return 0;
}

// post_handler，在函数执行后调用，记录结束时间并计算执行时长
static void post_handler(struct kprobe *p, struct pt_regs *regs, unsigned long flags)
{
    ktime_t end_time = ktime_get(); // 记录结束时间
    ktime_t duration = ktime_sub(end_time, start_time); // 计算持续时间
    printk(KERN_INFO "%s execution time: %lld ns\n", p->symbol_name, ktime_to_ns(duration));
}

// 初始化kprobe
static int __init kprobe_init(void)
{
    kp.pre_handler = pre_handler;
    kp.post_handler = post_handler;
    kp.symbol_name = "do_filp_open";

    if (register_kprobe(&kp) < 0) {
        printk(KERN_ERR "Failed to register kprobe\n");
        return -1;
    }
    printk(KERN_INFO "Kprobe registered for %s\n", kp.symbol_name);
    return 0;
}

// 清理kprobe
static void __exit kprobe_exit(void)
{
    unregister_kprobe(&kp);
    printk(KERN_INFO "Kprobe unregistered\n");
}

module_init(kprobe_init);
module_exit(kprobe_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A kprobe example to measure function execution time");